#include <iostream>
#include "myrealize.hpp"
#include <opencv4/opencv2/opencv.hpp>

using namespace std;
using namespace cv;

#define red 0
#define blue 1

int main()
{
    VideoCapture cap("./video/armor.mp4");

    Mat src;       // 用来暂存图片某一帧
    Mat src_;      // 经过预处理之后
    Mat src_bin;   // be used to find contours
    Mat src_hsv;   // 实际上hsv的优势可能更加明显
    
    vector<vector<Point>> contours;
    vector<vector<Point>> contours_;                        //经过初步筛选之后的轮廓

    vector<armorPiece> armors;

    int color_flag = blue;

    // 主循环
    while(1)
    { 
        
        if(!cap.read(src)) break;
        //*********************************************preprocessing
        cv::GaussianBlur(src,src_,cv::Size(5,5),5,5);
        //*********************************************

        toHsvBin(src_,src_bin,blue);
        /*************************************************************
         利用RGB来找轮廓噪声太大了
         *************************************************************/

        /**************************************************重建全黑图像
         * Mat black(src.size(),CV_8UC1,Scalar(0,0,0));
         * 首先提取到了某一帧图片
         * split(src, channels);
         * if(color_flag == red)
         * {
         *     midImage = channels.at(2) - channels.at(0);
         * }
         * else
         * {
         *     midImage = channels.at(0) - channels.at(2);
         * }
         * 阈值分割，使得得到较好结果的方法
         * double th = threshold(midImage, binImage, 120, 255, THRESH_BINARY|THRESH_OTSU);
         * if(th-10 > 0)
         * {
         *     threshold(midImage,binImage, th-10, 255, THRESH_BINARY);
         * } 
        ****************************************************************/

        // Select the contours that meet the condition.
        contoursSelect(src,src_bin,contours,contours_);
        // Select the armors that meet the condition.
        matchLightBar(src,contours_,armors);
        // Sort the armors
        sortArmors(armors);
        // cout<<armors.size()<<endl;
        // only nearest
        if(armors.size() > 0 && armors.size() < 4)
        {
            for(int i = 0; i < armors.size(); i++)
            {
                armors[i].drawArmor(src);
            }
        }

        imshow("source_binary_version",src_bin);
        imshow("source",src);
        waitKey(20);
    
    // avoid segment fault
    contours.clear();
    contours_.clear();
    armors.clear();
    }
    cap.release();
    return 0;
}